using System;
using System.Collections.Generic;
using ExcelTemplateEngine.Configuration;

namespace ExcelTemplateEngine.Infrastructure.Performance
{
    public interface IPerformanceMonitor
    {
        /// <summary>
        /// 开始性能计时
        /// </summary>
        IPerformanceScope BeginOperation(string operationName);
        
        /// <summary>
        /// 记录操作性能
        /// </summary>
        void RecordOperation(string operationName, TimeSpan duration, Dictionary<string, object>? metrics = null);
        
        /// <summary>
        /// 获取性能统计
        /// </summary>
        PerformanceStatistics GetStatistics();
        
        /// <summary>
        /// 重置统计数据
        /// </summary>
        void Reset();
    }
    
    public interface IPerformanceScope : IDisposable
    {
        /// <summary>
        /// 添加指标
        /// </summary>
        void AddMetric(string key, object value);
        
        /// <summary>
        /// 设置操作结果
        /// </summary>
        void SetResult(bool success, string? message = null);
    }
    
    public class PerformanceStatistics
    {
        public Dictionary<string, OperationStats> Operations { get; set; } = new();
        public DateTime StartTime { get; set; }
        public DateTime LastResetTime { get; set; }
        public int TotalOperations { get; set; }
    }
    
    public class OperationStats
    {
        public string OperationName { get; set; } = string.Empty;
        public int Count { get; set; }
        public TimeSpan TotalDuration { get; set; }
        public TimeSpan MinDuration { get; set; } = TimeSpan.MaxValue;
        public TimeSpan MaxDuration { get; set; } = TimeSpan.MinValue;
        public TimeSpan AverageDuration => Count > 0 ? TimeSpan.FromTicks(TotalDuration.Ticks / Count) : TimeSpan.Zero;
        public int SuccessCount { get; set; }
        public int FailureCount { get; set; }
        public DateTime LastExecuted { get; set; }
    }
}